﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Quartz;
using ServiceContainer.Commom;
using YouWei.Infrastructure.Entity;
using YouWei.Infrastructure.Enums;
using YouWei.Infrastructure.Service;
using YouWei.Utility;

namespace ServiceContainer.Jobs
{
    public class ErrorReminderJob : IJob
    {
        private int m_ErrorCount = 5;//异常数目，当大于该数值时发送异常提醒信息
        private List<string> listMobile = new List<string>()
        {
            "13436300382",  //苏长城
            //"18612012629",  //xu yang
            "18583683934"  //kun dong
        };
        JobEnum jobEnum = JobEnum.ErrorReminderJob;//作业ID
        public void Execute(IJobExecutionContext context)
        {
            var svJobRecord=new JobRecordService();
            var lastDataRecordTime = DateTime.Now.AddYears(-1);
            //获取最后一次执行作业的时间
            var oLastJobRecordInfo = svJobRecord.GetLastExcuteJobRecordInfo(jobEnum);
            if (oLastJobRecordInfo != null && !oLastJobRecordInfo.CreatedDate.IsNullDateTime())
            {
                lastDataRecordTime = oLastJobRecordInfo.CreatedDate;
            }
            else
            {
                oLastJobRecordInfo = new JobRecord();
            }

            int errCount = svJobRecord.GetErrorCount(101, lastDataRecordTime);
            if (errCount >= m_ErrorCount)
            {
                //终止短信发送
                AppAlarmHelper.SwitchTriiger = false;

                string mailBody = $"短信发送作业，在【{lastDataRecordTime.ToDisplay("yyyy-MM-dd HH:mm:ss")}】 - 【{DateTime.Now.ToDisplay("yyyy-MM-dd HH:mm:ss")}】之间共计发生了{errCount}条错误信息，请检查,当前程序已被迫终止！！！";
                //发送短信提醒
                ChannelShortMsgHelper.SendProductMsg(string.Join(",", listMobile), mailBody);

                oLastJobRecordInfo.CreatedDate = DateTime.Now;
               
            }
            else
            {
                oLastJobRecordInfo.CreatedDate = lastDataRecordTime;
            }
            oLastJobRecordInfo.JobId = (int)jobEnum;
            svJobRecord.Insert(oLastJobRecordInfo);
        }

    }
}
